package edu.zcmu.seckill.config;

import com.google.common.util.concurrent.RateLimiter;
import edu.zcmu.seckill.interceptor.IpUrlLimitInterceptor;
import edu.zcmu.seckill.interceptor.RequestLimiterInterceptor;
import edu.zcmu.seckill.interceptor.SysInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class MyConfiguration extends WebMvcConfigurationSupport {

    @Value("${zcmu.limiter.number}")
    private Integer LimiterNumber;
    // 过滤器跨域配置
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();

        // 允许跨域的头部信息
        config.addAllowedHeader("*");
        // 允许跨域的方法
        config.addAllowedMethod("*");
        // 可访问的外部域
        config.addAllowedOrigin("*");
        // 需要跨域用户凭证（cookie、HTTP认证及客户端SSL证明等）
        //config.setAllowCredentials(true);
        //config.addAllowedOriginPattern("*");

        // 跨域路径配置
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }


    //控制恶意请求刷新。
    @Bean
    IpUrlLimitInterceptor getIpUrlLimitInterceptor() {
        return new IpUrlLimitInterceptor();
    }
    //控制高流量
    @Bean
    RequestLimiterInterceptor getRequestLimiterInterceptor(){
        return new RequestLimiterInterceptor();
    }

    @Bean
    SysInterceptor getSysInterceptor(){
        return new SysInterceptor();
    }
    @Bean
    RateLimiter rateLimiter(){

        return RateLimiter.create(LimiterNumber);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getSysInterceptor()).addPathPatterns("/seckill/pay/**"
                ,"/seckill/seckill-order/**","/seckill/order/**"
                ,"/captcha/**","/seckill/user/getAllOrder","/seckill/user/delUserOrder"
                ,"/seckill/user/alterPassword","/seckill/user/getUserInfo");
        registry.addInterceptor(getRequestLimiterInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(getIpUrlLimitInterceptor()).addPathPatterns("/**").
                excludePathPatterns("/seckill/product/**","/seckill/user/**","/seckill/seckill-product/**","/admin/**");
        super.addInterceptors(registry);
    }


}
